package com.bcx.crm.spring_boot.springMVC.sse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * Created by ys on 2018/4/23.
 * 测试失败-----springBoot  107
 */
@Controller
public class SseController {
    @RequestMapping(value = "/push",produces = "text/event-stream")
    @ResponseBody
    public void push(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //媒体类型为 text/event-stream
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.println("data:Hello World");
        out.println("event:load");
        out.println("id:140312");
        out.println();
        out.flush();
        out.close();

    }
    @RequestMapping(value = "/push1",produces = "text/event-stream")
    @ResponseBody
    public String push1(HttpServletResponse response){
        Random random = new Random();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("charset=UTF-8");
        response.setContentType("text/event-stream");
//        response.setHeader("Content-Type","text/html;charset=utf-8");
        response.setHeader("Content-Type","text/event-stream");
        return "data:Testing 1,2,3"+random.nextInt()+"\n\n";
    }
    @RequestMapping("/getSseHtml")
    public String getSseHtml(){
        return "crm/private/sse/sse";
    }
}
